package com.ybkj.daijia.api.baidu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class BaiduApiImpl implements BaiduApi {

    private static final Logger logger = LoggerFactory.getLogger(BaiduApiImpl.class);

    @Autowired
    private RestTemplate restTemplate;
    private Logger locationLogger = LoggerFactory.getLogger("location");

    //    public Map<String, Double> getPreCountMilleageAndTime(String startLatitude, String startLongitude, String endLatitude, String endLongitude) {
//        return getPreCountMilleageAndTime(startLatitude, startLongitude, endLatitude, endLongitude, true);
//    }
//
//    public Map<String, Double> countMilleage(String startLatitude, String startLongitude, String endLatitude, String endLongitude) {
//        return getPreCountMilleageAndTime(startLatitude, startLongitude, endLatitude, endLongitude, false);
//    }
//    public Map<String, Double> getPreCountMilleageAndTime(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
//        return getPreCountMilleageAndTime(String.valueOf(startLatitude), String.valueOf(startLongitude), String.valueOf(endLatitude), String.valueOf(endLongitude), true);
//    }
    @Autowired
    private SettingUtils settingUtils;

    private Long[] getPreCountMilleageAndTime(String startLatitude, String startLongitude,
        String endLatitude, String endLongitude, boolean containTime) {
        Map<String, Object> map = new HashMap<String, Object>();
        String origins = startLatitude + "," + startLongitude;
        String destinations = endLatitude + "," + endLongitude;
        map.put("origins", origins);
        map.put("destinations", destinations);
        Long[] re = new Long[2];
        try {
            String url = containTime ? PRE_COUNT_MILEAGE_AND_TIME : PRE_COUNT_MILEAGE;
            String forObject = restTemplate.getForObject(url, String.class, map);
            if (null != forObject) {
                JSONObject obj = JSON.parseObject(forObject);
                if (0 == obj.getInteger("status")) {
                    JSONArray result = obj.getJSONArray("result");
                    if (0 < result.size()) {
                        JSONObject jo = result.getJSONObject(0);
                        JSONObject distance = jo.getJSONObject("distance");
                        JSONObject duration = jo.getJSONObject("duration");
                        re[0] = distance.getLong("value");
                        if (containTime) {
                            re[1] = duration.getLong("value");
                        }
                        return re;
                    }
                } else {
                    logger.error(
                        "访问百度地图api,获取预估的路程和时间失败,msg={}, params : startLatitude {}, startLongitude {}, endLatitude {}, endLongitude {}, obj {} "
                            +
                            ", containTime", obj.getString("message"), startLatitude,
                        startLongitude, endLatitude, endLongitude, containTime, obj);
                }
            }
        } catch (Exception e) {
            logger.error(
                "访问百度地图api,获取预估的路程和时间失败,msg={}, params : startLatitude {}, startLongitude {}, endLatitude {}, endLongitude {}, \nerror {}"
                    +
                    ", containTime", e.getMessage(), startLatitude, startLongitude, endLatitude,
                endLongitude, containTime, e);
        }
        return null;
    }

//    public Map<String, Double> getPreCountMilleageAndTime(String startLatitude, String startLongitude, String endLatitude, String endLongitude) {
//        return getPreCountMilleageAndTime(startLatitude, startLongitude, endLatitude, endLongitude, true);
//    }
//
//    public Map<String, Double> countMilleage(String startLatitude, String startLongitude, String endLatitude, String endLongitude) {
//        return getPreCountMilleageAndTime(startLatitude, startLongitude, endLatitude, endLongitude, false);
//    }
//    public Map<String, Double> getPreCountMilleageAndTime(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
//        return getPreCountMilleageAndTime(String.valueOf(startLatitude), String.valueOf(startLongitude), String.valueOf(endLatitude), String.valueOf(endLongitude), true);
//    }

    /***
     *
     * @param startLatitude
     * @param startLongitude
     * @param endLatitude
     * @param endLongitude
     * @return 单位米
     */
    @Override
    public Long[] countMilleage(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
        return getPreCountMilleageAndTime(String.valueOf(startLatitude), String.valueOf(startLongitude), String.valueOf(endLatitude), String.valueOf(endLongitude), true);
    }

    @Override
    public Double getDistance(String locsString) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> map = new LinkedMultiValueMap();
        Setting setting = settingUtils.get();
        map.add(AK_P, setting.getBaiduKey());
        map.add(POINT_LIST_P, locsString);
        map.add(SUPPLEMENT_MODE, DRIVING);
        HttpEntity requestBody = new HttpEntity(map, headers);
        try {
            ResponseEntity<String> re = restTemplate
                .postForEntity(PATH_DERECT, requestBody, String.class);
            JSONObject jsonObject = JSON.parseObject(re.getBody());
            Double aDouble = null;
            if (OK == jsonObject.getInteger(STATUS)) {
                aDouble = jsonObject.getDouble(DISTANCE);
            }
            if (aDouble == null) {
                locationLogger.error("baiduApi calculate miles error, {}", jsonObject);
            }
            return aDouble;
        } catch (Exception e) {
            locationLogger.error("baiduApi calculate miles error, {}", e);
        }
        return null;
    }


}
